#!/usr/bin/python
# -*- coding: UTF-8 -*-

"""
Description: Dynamic import module

"""
import importlib
import os
import sys
from importlib import import_module

from kpextension.wrapper_extension import WrapperExtension
from kptest.api.apimodule import ApiModule
from setuptools import find_packages


def import_sub_dir(base_dir: str):
    for _file in os.listdir(base_dir):
        _path = os.path.join(base_dir, _file)
        if os.path.isdir(_path):
            import_sub_dir(_path)
        if (not _file.endswith(".py")) or _file.startswith("__"):
            continue
        import_file("extension.api", _path)


def import_file(root: str, file_path: str):
    module_name = file_path.replace(os.sep, '.').split(".")[:-1]
    if root not in sys.modules:
        raise Exception("Module %s is not imported." % root)
    root_module = sys.modules[root].__path__[0].replace(os.sep, '.').split(".")
    for _k in root_module:
        if _k in module_name:
            module_name.remove(_k)
    module_name = "{}.{}".format(root, ".".join(module_name))
    return importlib.import_module(module_name)


def register_extension_api(device, path: str):
    api = ApiModule(name="kptest_extension_api", version="1.0",
                    description="KunePeng Open Test Library Extension APIs.")
    device.register_api(api)
    for module_name in find_packages(os.path.dirname(path)):
        module = import_module('.%s' % module_name, package="extension.api")
        if hasattr(module, 'init_module'):
            module.init_module(api)


def register_extension_wrapper(device, path: str):
    wrapper_extension = WrapperExtension(device)
    dispatcher_module = wrapper_extension.create(name="kptest_extension_dispatcher", version="1.0",
                                                 description="KunePeng Open Test Library Extension Dispatchers.")
    wrapper_extension.register(dispatcher_module)
    for module_name in find_packages(os.path.dirname(path)):
        module = import_module('.%s' % module_name, package="extension.wrapper")
        if hasattr(module, 'init_module'):
            module.init_module(dispatcher_module, device)
        if not hasattr(module, "__all__"):
            continue
        for _cname in module.__all__:
            class_spec = getattr(module, _cname)
            dispatcher_module.add_wrapper_class((class_spec.command_types, class_spec.host_types, class_spec))
